import React, {Component} from 'react';
import GridTable from '../components/display/gridTable';
import ScModal from '../components/feedback/scModal';
import { Button, Select, Input } from 'antd';
import { getPermissionList,
    getUserMenuList,
    editPermission,
    deletePermission
} from '../fetch/fetchApi';
import TreeTransfer from '../components/dataEntry/treeTransfer';
import PropTypes from "prop-types";
const Option = Select.Option;

class Home extends Component {
    constructor () {
        super();
        this.init();
        this.state = {
            gridData: null,
            modalVisible: !1,
            modalTitle: '',
            fromData: [],
            target: [],
            inputValue: '',
            defaultTitle: '',
            defaultType: undefined,
            confirmLoading: !1,
            loading: !1,
            pagination: {
                current: 1,
                defaultCurrent: 1,
                defaultPageSize: 10,
                onChange: this.tableChange.bind(this)
            }
        }
    }

    static contextTypes = {
        router: PropTypes.object.isRequired
    }

    tableChange (e) {
        const page = {...this.state.pagination};
        page.current = e;
        this.setState({
            pagination: page
        });
    }

    init () {
        this.title = '权限管理';
        this.subTitle = '权限列表';
        this.selectedKey = ['000201'];
        this.openKeys = ['00', '0002'];
        this.tableColumns = [
            {
                title: '权限名称',
                dataIndex: 'title',
                key: 'title',
            }, {
                title: '类别',
                dataIndex: 'info',
                key: 'info',
            },
            {
                title: '操作',
                key: 'action',
                render: (text, record) => (
                    <div className="action-wrap">
                        <Button type="danger" id={record.key} onClick={this.deletePression.bind(this)}>删除</Button>
                        <Button type="primary"
                                id={record.key}
                                title="编辑权限"
                                deftitle={record.title}
                                deftype = {record.type}
                                detarget = {record.paramStr}
                                onClick={this.openNewPression.bind(this)}>编辑</Button>
                    </div>
                )
            }
        ];
    }

    componentWillMount () {
        this.params = {};
        this.getPermissionListCb();
        this.getUserMenuList();
        this.getUserMenuList1();
    }

    getPermissionListCb () {
      this.getPermissionList().then(() => {
        this.setState({
          loading: !1
        });
      });
    }

    async getPermissionList () {
        this.setState({
          loading: !0
        });
        try {
            const resData = await getPermissionList();
            let gridData = resData.data.data;
            for (let i of gridData) {
                i.type === 1 && (i.info = '菜单读权限');
                i.type === 2 && (i.info = '菜单写权限');
                i.type === 3 && (i.info = '数据城市查询权限');
            }
            const page = {...this.state.pagination};
            page.total = gridData.length;
            this.setState({
                modalVisible: !1,
                gridData,
                pagination: page
            });
        } catch (e) {
            console.log(e);
        }
    }

    async getUserMenuList () {
        try {
            const resData = await getUserMenuList({
                type: 2
            });
            const formatBeforeData = resData.data.data;
            const fromData = JSON.parse(JSON.stringify(formatBeforeData).replace(/id/g,'key').replace(/childList/g, 'children'));
            this.setState({
                fromData: fromData || []
            });
        } catch (e) {
            console.log(e);
        }
    }

    async getUserMenuList1 () {
        try {
            const resData = await getUserMenuList();
            this.setState({
                'menuList': resData.data.data
            })
        } catch (e) {
            console.log(e);
        }
    }

    openNewPression (e) {
        this.setState({
            modalVisible: !0,
            modalTitle: e.target.title,
            permissionId: e.target.id,
            defaultTitle: e.target.getAttribute('deftitle'),
            defaultType: e.target.getAttribute('deftype') || undefined,
            defaultTarget: e.target.getAttribute('detarget') || undefined,
            target: e.target.getAttribute('detarget') ? e.target.getAttribute('detarget').split(',') : []
        });
        this.params = {
            permissionId: e.target.id,
            title: e.target.getAttribute('deftitle'),
            type: e.target.getAttribute('deftype'),
            paramStr: e.target.getAttribute('detarget')
        };
    }

    async editPermission (params) {
        this.setState({
          confirmLoading: !0
        });
        try {
            const param = params;
            const resData = await editPermission(param);
            this.setState({
              confirmLoading: !1
            });
            resData.data.code === '200' && this.getPermissionListCb();
        } catch (e) {
            console.log(e);
        }
    }

    async deletePression (e) {
        try {
            const param= {id: e.target.id};
           const resData = await deletePermission(param);
           resData.data.code === '200' && this.getPermissionListCb();
        } catch (e) {
            console.log(e);
        }
    }

    setInputVale (e) {
        this.params.title = e.target.value;
        this.setState({
            defaultTitle: e.target.value
        });
    }

    handleChange (e) {
        this.setState({
            defaultType: e
        });
        this.params.type = e;
    }

    handleTransferChange (target) {
        this.setState({
            target
        });
        this.params.paramStr = target.length ? target.join(',') : '';
    }

    cancel () {
        this.setState({
            modalVisible: !1
        });
    }

    render () {
        const Content = <div className="sc-page-content">
            <div className="page-toolbar">
                <Button type="primary"
                        title="新增权限"
                        deftitle=""
                        deftype = ""
                        onClick={this.openNewPression.bind(this)}>新增</Button>
            </div>
            <div className="page-panel">
                <GridTable data={this.state.gridData} postyle="table-center" columns={this.tableColumns} pagination={this.state.pagination} loading={this.state.loading}/>
            </div>
        </div>;
        return <div>
            {Content}
            <ScModal
                modalVisible={this.state.modalVisible}
                modalTitle={this.state.modalTitle}
                modalContent={<div>
                    <div className="modal-list">
                        <Input placeholder="请输入权限名称" value={this.state.defaultTitle} onChange={this.setInputVale.bind(this)} />
                    </div>
                    <div className="modal-list">
                        {
                            <Select value={this.state.defaultType} onChange={this.handleChange.bind(this)} className="modal-select" placeholder="请选择权限类别">
                                <Option value="1">菜单读权限</Option>
                                <Option value="2">菜单分配权限</Option>
                                <Option value="3">数据城市查询权限</Option>
                            </Select>
                        }
                    </div>
                    <div className="modal-list">
                        <TreeTransfer
                            source={this.state.fromData}
                            target={this.state.target}
                            showSearch
                            sourceTitle="可选权限"
                            targetTitle="已有权限"
                            onChange={this.handleTransferChange.bind(this)} />
                    </div>
                </div>}
                handle = {this.editPermission.bind(this)}
                cancel = {this.cancel.bind(this)}
                confirmLoading={this.state.confirmLoading}
                param = {this.params}
            />
        </div>
    }
}

export default Home;